import csv, codecs
import os

from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.http import JsonResponse, HttpResponse
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.utils.http import urlquote

from system.models import Line
from utils.common.db_handle import insert_line


@method_decorator(login_required, name='get')
class PeerView(TemplateView):
    """Peer 页面视图"""

    template_name = 'backend/peer.html'

    def get_context_data(self, **kwargs):
        province_nums = Line.objects.values('province').annotate(num=Count('province')).values('province', 'num')
        province_list = [i['province'] for i in province_nums]  # 所有的省份

        context = super(PeerView, self).get_context_data(**kwargs)
        context['province_list'] = province_list

        return context


@method_decorator(login_required, name='get')
class PeerListView(View):
    """Peer list 数据"""

    def get(self, request):
        condition = dict()
        draw = request.GET.get('draw')
        page = int(request.GET.get('page', 0))
        limit = int(request.GET.get('pagesize', 10))
        province = request.GET.get('province')
        status = request.GET.get('status')

        start, end = (page - 1) * limit, page * limit  # 计算要查询的数据数量
        ret = {'recordsFiltered': None, 'data': [], 'draw': draw, 'recordsTotal': 0}
        # fields = ['ppp_usr', 'peer', 'status', 'end_point', 'city', 'pub_ip', 'operator', 'netns']

        # 过滤查询
        if province != "0":
            condition['province'] = province
            condition['status'] = status

        line_list = []
        for line in Line.objects.filter(**condition)[start: end]:
            line_list.append({
                'ppp_usr': line.ppp_usr,
                'peer': line.peer,
                'status': line.get_status_display(),
                'end_point': line.end_point,
                'city': line.city,
                'pub_ip': line.pub_ip,
                'operator': line.get_operator_display(),
                'netns': line.netns,

            })

        ret['data'] = line_list
        ret['recordsTotal'] = len(line_list)
        ret['recordsFiltered'] = Line.objects.count()

        return JsonResponse(ret)


@method_decorator(login_required, name='post')
class PeerUploadView(View):
    """上传 CSV"""

    def post(self, request):
        ret = {'code': 0, 'msg': '导入成功'}
        files_obj = request.FILES.get('files')

        base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        upload_path = os.path.join(os.path.join(base_dir, 'media'), 'upload')
        file_path = os.path.join(upload_path, files_obj.name)  # D:\v1\CBS\CBS\media\upload\江苏泰州电信.csv

        # 判断格式
        if not files_obj.name.endswith('.csv'):
            ret['code'] = 10032
            ret['msg'] = '请导入 csv 文件！'
            return JsonResponse(ret)

        try:
            # 保存
            with open(file_path, 'wb') as f:
                for i in files_obj.chunks():
                    f.write(i)

            # 读取并插入到数据库
            status = insert_line(file_path)
            if not status:
                # 重复插入
                ret['code'] = 10033
                ret['msg'] = '重复导入'

            # 删除文件
            os.remove(file_path)
        except Exception as e:
            ret['code'] = 10034
            ret['msg'] = '其他错误，请检查 CSV列名'
            print(e)
            os.remove(file_path)

        return JsonResponse(ret)


@method_decorator(login_required, name='get')
class PeerBatchExportView(View):
    """批量导出"""

    def get(self, request):
        condition = dict()
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="all_peer.csv"'

        province = request.GET.get('province')
        status = request.GET.get('status')

        writer = csv.writer(response)
        response.write(codecs.BOM_UTF8)  # 解决中文乱码
        writer.writerow(['ppp_usr', 'peer', 'status', 'end_point', 'city', 'pub_ip', 'operator', 'netns'])

        # 过滤条件，单条导出
        if province:
            condition['province'] = province
            condition['status'] = status
            response['Content-Disposition'] = 'attachment; filename="{}.csv"'.format(urlquote(province))

        for line in Line.objects.filter(**condition).all():
            writer.writerow([
                line.ppp_usr, line.peer, line.get_status_display(), line.end_point, line.city, line.pub_ip,
                line.get_operator_display(), line.netns,
            ])

        return response
